import * as types from './mutation-types'
import http from '@/utils/HttpClient'
import globalData from '@/utils/GlobalData'

const state = {
  teacherInfo: {},
  unGradAndDelayStudents: null,
  gradStudents: null,
  ranks: null
}

const mutations = {
  [types.LOAD_TEACHER_INFO] (_state, data) {
    _state.teacherInfo = data
  },
  [types.LOAD_UNGRAD_STUDENTS] (_state, data) {
    _state.unGradAndDelayStudents = data
  },
  [types.LOAD_GRAD_STUDENTS] (_state, data) {
    _state.gradStudents = data
  },
  [types.LOAD_TEACHER_RANK] (_state, data) {
    _state.ranks = data
  }
}

const actions = {

  updateTeacherTask ({ commit, state }, { taskId, studentId, status, score }) {
    var data:any = state.unGradAndDelayStudents
    var student = data.find((e) => {
      return e.studentId === studentId
    })
    var task = student.tasks.find(e => e.id === taskId)
    task.status = status
    task.score = score
    if (status === 2) {
      student.completeTaskCount++
      student.unScoreCount--
    }
    if (status === 7 || status === 5) {
      student.pendingCount--
    }
  },

  async getTeacherInfo ({ commit }) {
    var data = await http.get({ url: 'teacher/teacherInfo' })
    commit(types.LOAD_TEACHER_INFO, data)
  },

  async getUnGradStudents ({ commit }) {
    var data = await http.get({ url: 'student/unGradByTeacher/' + globalData.appUser.id })
    commit(types.LOAD_UNGRAD_STUDENTS, data)
  },

  async getGradStudents ({ commit, state }) {
    if (state.gradStudents && state.gradStudents.items.length === state.gradStudents.totalCount) {
      return
    }
    var data = await http.get({ url: 'student/gradByTeacher/' + globalData.appUser.id,
      data: {
        SkipCount: state.gradStudents == null ? 0 : state.gradStudents.items.length,
        MaxResultCount: 10
      } })
    if (state.gradStudents !== null) {
      var items = state.gradStudents.items.concat(data.items)
      data.items = items
    }
    commit(types.LOAD_GRAD_STUDENTS, data)
  },

  async getTeacherRank ({ commit, state }) {
    if (state.ranks && state.ranks.items.length === state.ranks.totalCount) {
      return
    }
    var data = await http.get({ url: 'rank/teacherRank',
      data: {
        SkipCount: state.ranks == null ? 0 : state.ranks.items.length,
        MaxResultCount: 20
      } })
    if (state.ranks !== null) {
      var items = state.ranks.items.concat(data.items)
      data.items = items
    }
    commit(types.LOAD_TEACHER_RANK, data)
  }
}

const getters = {
  unGradStudents: (_state) => {
    return _state.unGradAndDelayStudents ? _state.unGradAndDelayStudents.filter(e => e.status === 0) : null
  },
  unGradAndDelayStudents: (_state) => {
    return _state.unGradAndDelayStudents
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
